package com.tomcat;


import com.tomcat.servlet.Request;
import com.tomcat.servlet.Response;
import com.tomcat.container.ApplicationContext;
import com.tomcat.container.DefaultSingletonBeanRegistry;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class UpUpOn {

    public static void main(String[] args) throws IOException {
        UpUpOn upUpOn = new UpUpOn();
        upUpOn.setUp(8085);
    }


    //解析用户请求数据
    public void handler(Socket socket) throws Exception {
        InputStream inputStream = socket.getInputStream();
        int available = inputStream.available();
        if (available == 0) {
            socket.getOutputStream().close();
            return;
        }
        byte[] bytes = new byte[available];
        int read = inputStream.read(bytes);
        String content = new String(bytes, StandardCharsets.UTF_8);
        //解析request信息 得到需要执行的方法
        Request request = new Request();
        Response response = new Response(socket.getOutputStream());
        getUriPath(request, content);
        response.GetWrite(execute(request));
        inputStream.close();
        response.Close();
    }

    public void setUp(Integer port) throws IOException {
        ServerSocket serverSocket = new ServerSocket(port);
        ApplicationContext applicationContext = new ApplicationContext(ApplicationContext.class);
        applicationContext.printMapping();
        while (true) {
            Socket socket = serverSocket.accept();
            new Thread(() -> {
                try {
                    handler(socket); // 将 socket 传递给 handler 方法
                } catch (Exception e) {
                    try {
                        socket.getOutputStream().close();
                    } catch (IOException es) {
                        es.printStackTrace();
                    }
                    e.printStackTrace();
                }
            }).start();
        }
    }


    public void getUriPath(Request request, String content) {
        if (content.equals("")) {
            System.out.println("你有一个空请求......");
        } else {
            String firstLine = content.split("\\n")[0];
            request.setMethod(firstLine.split("\\s")[0]);
            request.setUrl(firstLine.split("\\s")[1]);
            if (request.getMethod().equals("POST")) {
                try {
                    request.setParam(content.substring(content.indexOf("{")));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public Object execute(Request request) throws ClassNotFoundException {
        if (!request.getMethod().equals("POST")) {
            return "只支持POST";
        }
        if (request.getParam() == null) {
            return "必须为JSON";
        }
        Object o = DefaultSingletonBeanRegistry.getMapping().get(request.getUrl());
        if (o == null) {
            return "404";
        }
        Method method = (Method) o;
        Class<?> aClass = Class.forName(method.getDeclaringClass().getName());
        Object invoke = null;
        try {
            invoke = method.invoke(aClass.newInstance(), request.getParam());
        } catch (Exception e) {
            e.printStackTrace();
            return "400";
        }
        return invoke.toString();
    }

}
